import { Injectable } from '@nestjs/common';
import { AuthenticationStrategy } from './authentication-strategy.interface';
import { UserService } from 'src/modules/user/user.service';
import { PasswordLoginDto } from './dto/password-login.dto';
import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';
import { ApiException } from 'src/common/filter/http-exception/api.exception';
import { ApiErrorCode } from 'src/common/enums/api-error-code.enum';

// username-password.strategy.ts
@Injectable()
export class UsernamePasswordStrategy implements AuthenticationStrategy {
  constructor(
    private readonly userService: UserService,
  ) { }

  async register(credentials: PasswordLoginDto): Promise<any> {
    return this.userService.create(credentials);
  }
  async authenticate(credentials: PasswordLoginDto): Promise<any> {

    const object = plainToInstance(PasswordLoginDto, credentials);
    const errors = await validate(object);
    console.error(errors)
    if (errors.length > 0) {
      throw new ApiException("param error", ApiErrorCode.USER_NOTEXIST)
    }

    // 执行用户名密码登录逻辑
    // 例如，验证用户名和密码是否匹配，并返回用户信息
    const user = await this.userService.findUserByUsername(credentials.username);

    if (!user) {
      return null; // 用户不存在
    }

    const isPasswordValid = credentials.password == user.password;

    if (!isPasswordValid) {
      return null; // 密码不匹配
    }

    return user; // 用户验证成功
  }
}
